<template>
  <el-dialog
    title="编辑计算公式"
    :modelValue="isOpen"
    :before-close="handleClose"
    append-to-body
    width="45%"
  >
    <div style="padding: 20px 30px">
      <component
        :is="typeComponent"
        :item="item"
        :cols="cols"
        :moreCols="moreCols"
        :dateCols="dateCols"
        @on-add="handleAdd"
        @on-date="handleDate"
      />
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleSave">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import formula from './formula';
  import _ from 'lodash';
  import { formulas } from './index';
  import request from '@/framework-core/axios';
  import website from '@/framework-core/config/website';
  export default {
    components: {
      ...formula
    },
    props: {
      isOpen: {
        type: Boolean,
        default: false
      },
      item: {
        type: Object,
        default: () => {}
      },
      widgetForm: {
        type: Object,
        default: () => {}
      }
    },
    data() {
      return {
        labels: [],
        values: [],
        content: '',
        showContent: '',

        firstDateProp: '',
        secondDateProp: '',
        dateUnit: '',
        addOrSubtract: '',
        timeType: '',

        type1: '',
        type2: '',

        cols: [],
        moreCols: [],
        dateCols: [],
        transWidgetForm: {}
      };
    },
    computed: {
      typeComponent() {
        return this.item.formulaType;
      }
    },
    mounted() {
      this.transformToAvueOptions(this.widgetForm).then((data) => {
        this.transWidgetForm = data;

        let cols = [];
        console.log(this.item);
        debugger;
        switch (this.item.formulaType) {
          case formulas.number: {
            this.moreCols = this.getColumn(this.isNotNumber);
            cols = this.getColumn(this.isNumber);
            break;
          }
          case formulas.timeDifference:
            cols = this.getColumn(this.isTimeDifference);
            break;
          case formulas.timeDifferenceRange:
            cols = this.getColumn(this.isTimeDifferenceRange);
            break;
          case formulas.date:
            cols = this.getColumn(this.isDate);
            this.dateCols = this.getColumn(this.isNumber);
            break;
        }

        this.cols = cols;
      });
    },
    methods: {
      async apiCalVerify(modelJson, formulaContent) {
        return request.post(
            website.baseUrl+ '/api/form/calculate/verify',
          modelJson,
          {
            params: {
              formulaContent
            }
          }
        );
      },
      handleClose() {
          this.$emit('on-close',"");
      },
      async handleSave() {
        const { formulaType } = this.item;
        if (formulaType === formulas.number && this.content) {
          try {
            await this.apiCalVerify(this.transWidgetForm, this.content);
          } catch ({ msg }) {
            this.$message.error(msg);
            return false;
          }
        }
        debugger
        if (
          this.item.formulaType === formulas.timeDifference &&
          this.type1 !== this.type2
        ) {
          this.$message.error('时间类型不同，之间无法做时差运算!');
        } else {
          this.saveA();
          this.handleClose();
        }
      },
      saveA() {
        this.$emit('on-save', {
          content: this.content,
          showContent: this.showContent,
          labels: this.labels,
          values: this.values,
          firstDateProp: this.firstDateProp,
          secondDateProp: this.secondDateProp,
          dateUnit: this.dateUnit,
          addOrSubtract: this.addOrSubtract,
          timeType: this.timeType
        });
      },
      handleAdd({ content, showContent, labels, values }) {
        this.showContent = showContent;
        this.content = content;
        this.labels = labels;
        this.values = values;
      },
      handleDate({
        showContent,
        firstDateProp,
        secondDateProp,
        dateUnit,
        type1,
        type2,
        addOrSubtract,
        timeType
      }) {
        this.showContent = showContent;
        this.firstDateProp = firstDateProp;
        this.secondDateProp = secondDateProp;
        this.dateUnit = dateUnit;
        this.type1 = type1;
        this.type2 = type2;
        this.addOrSubtract = addOrSubtract;
        this.timeType = timeType;
      },
      columnWithGrop() {
        const newColumn = [];
        const { column, group } = this.transWidgetForm;
        if (column?.length) {
          column.map((col) => {
            newColumn.push(col);
          });
        }
        if (group?.length) {
          group.map((item) => {
            if (item?.column) {
              const childrenColumn = item.column;
              childrenColumn.map((child) => {
                newColumn.push(child);
              });
            }
          });
        }
        console.log(newColumn);
        return newColumn;
      },
      // 表单设计器配置项 转化为 Avue配置项
      transformToAvueOptions(obj, isPreview = false) {
        const _this = this;
        return new Promise((resolve, reject) => {
          try {
            const data = _this.deepClone(obj);
            for (let i = 0; i < data.column.length; i++) {
              const col = data.column[i];

              if (isPreview) {
                // 预览调整事件中的this指向
                let event = ['change', 'blur', 'click', 'focus'];
                event.forEach((e) => {
                  if (col[e])
                    col[e] = eval((col[e] + '').replace(/this/g, '_this'));
                });
                if (col.event)
                  Object.keys(col.event).forEach(
                    (key) =>
                      (col.event[key] = eval(
                        (col.event[key] + '').replace(/this/g, '_this')
                      ))
                  );
              }

              if (
                col.type == 'dynamic' &&
                col.children &&
                col.children.column &&
                col.children.column.length > 0
              ) {
                const c = col.children.column;
                c.forEach((item) => {
                  delete item.subfield;
                });
                this.transformToAvueOptions(col.children, isPreview).then(
                  (res) => {
                    col.children = res;
                  }
                );
              } else if (col.type == 'group') {
                if (!data.group) data.group = [];

                const group = {
                  label: col.label,
                  icon: col.icon,
                  prop: col.prop,
                  arrow: col.arrow,
                  collapse: col.collapse,
                  display: col.display
                };
                this.transformToAvueOptions(col.children, isPreview).then(
                  (res) => {
                    group.column = res.column;
                    data.group.push(group);
                  }
                );
                data.column.splice(i, 1);
                i--;
              } else if (
                ['checkbox', 'radio', 'tree', 'cascader', 'select'].includes(
                  col.type
                )
              ) {
                if (col.dicOption === '1') {
                  delete col.dicUrl;
                  delete col.dicMethod;
                  delete col.dicQuery;
                  delete col.dicQueryConfig;
                } else if (col.dicOption === '2') {
                  delete col.dicData;
                  if (col.dicQueryConfig && col.dicQueryConfig.length > 0) {
                    const query = {};
                    col.dicQueryConfig.forEach((q) => {
                      if (q.key && q.value) query[q.key] = q.value;
                    });
                    col.dicQuery = query;
                    delete col.dicQueryConfig;
                  } else delete col.dicQueryConfig;
                }
                delete col.dicOption;
              } else if (['upload'].includes(col.type)) {
                if (col.headersConfig && col.headersConfig.length > 0) {
                  const headers = {};
                  col.headersConfig.forEach((h) => {
                    if (h.key && h.value) headers[h.key] = h.value;
                  });
                  col.headers = headers;
                } else delete col.headers;
                delete col.headersConfig;

                if (col.dataConfig && col.dataConfig.length > 0) {
                  const data = {};
                  col.dataConfig.forEach((h) => {
                    if (h.key && h.value) data[h.key] = h.value;
                  });
                  col.data = data;
                } else delete col.data;
                delete col.dataConfig;
              }
            }
            resolve(data);
          } catch (e) {
            reject(e);
          }
        });
      },
      getColumn(callback) {
        const newColumn = this.columnWithGrop();
        const cols = _.filter(newColumn, (item) => {
          return callback(item, this.item);
        });

        const dynamicCols = _.filter(newColumn, { type: 'dynamic' });
        if (dynamicCols.length) {
          const dyns = [];
          dynamicCols.map((dyncol) => {
            const childColumn = {
              column: [],
              label: '',
              prop: ''
            };
            const { label, prop } = dyncol;
            if (dyncol?.children?.column?.length) {
              const childrenCols = dyncol.children.column;
              const checkChildrenCols2 = _.filter(childrenCols, (item) => {
                return callback(item, this.item);
              });
              if (checkChildrenCols2.length) {
                childColumn.column = checkChildrenCols2;
                childColumn.label = label;
                childColumn.prop = prop;
              }
            }

            if (childColumn.column.length) {
              dyns.push(childColumn);
            }
          });
          if (dyns.length) {
            return _.concat(dyns, cols);
          }
        }
        return cols;
      },
      isDate(item, currentItem) {
        return this.isTimeDifference(item, currentItem);
      },
      isTimeDifference(
        item,
        currentItem,
        check = [
          'year',
          'month',
          'week',
          'date',
          'time',
          'datetime',
          'dateampm'
        ]
      ) {
        const { type, formulaType, prop } = item;
        if (prop === currentItem.prop) {
          return false;
        }
        const isFormula =
          type === formulas.type && formulaType === formulas.date;
        if (check.includes(type) || isFormula) {
          return true;
        }
        return false;
      },
      isTimeDifferenceRange(item, currentItem) {
        return this.isTimeDifference(item, currentItem, [
          'daterange',
          'timerange',
          'datetimerange'
        ]);
      },
      isNotNumber(item, currentItem) {
        if (item.display === false) {
          return false;
        }
        return !this.isNumber(item, currentItem);
      },
      isNumber(item, currentItem) {
        const { type, formulaType, prop } = item;
        if (prop === currentItem.prop) {
          return false;
        }
        const isFormula =
          type === formulas.type && formulaType !== formulas.date;
        if (type === 'number' || isFormula) {
          return true;
        }
        return false;
      }
    }
  };
</script>
